from datetime import datetime
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from marshmallow import Schema, fields, validate

app = Flask(__name__)

ma = Marshmallow()
ma.init_app(app)


class UserSchema(Schema):
    name = fields.String(validate=validate.Length(min=1))
    permission = fields.String(required=True, validate=validate.OneOf(["read", "write", "admin"]))
    age = fields.Integer(required=True, error_messages={"required": "age必须填写不！"},
                         validate=validate.Range(min=18, max=40, error="age取值范围：age>=18 and age<=40"))


@app.route("/")
def index():
    # user_data = {"name": "悟空", "email": "wukong@stones.com"}
    """
    age = fields.Integer(validate=validate.Range(min=18, max=40))
    没通过报错：
    marshmallow.exceptions.ValidationError: {'email': ['Unknown field.']}
    """

    # user_data = {"name": "悟空"}
    """
    age = fields.Integer(validate=validate.Range(min=18, max=40))
    在其他几个字段没有被设置为required=True的时候，验证是通过的，通过： 
    {'name': '悟空'}
    """

    user_data = {"name": "悟空"}
    """
    age = fields.Integer(required=True,validate=validate.Range(min=18, max=40))
    当设置了required=True的时候，没通过报错：
    marshmallow.exceptions.ValidationError: {'age': ['Missing data for required field.']}

    age = fields.Integer(required=True,error_messages={"required":"age必须填写不！"},validate=validate.Range(min=18, max=40))
    marshmallow.exceptions.ValidationError: {'age': ['age必须填写不！']}
    """

    user_data = {"name": "悟空", "age": 16, }
    """
    age = fields.Integer(required=True,error_messages={"required":"age必须填写不！"},validate=validate.Range(min=18, max=40,error="age取值范围：age>=18 and age<=40"))
    marshmallow.exceptions.ValidationError: {'age': ['age取值范围：age>=18 and age<=40']}
    """

    user_data = {"name": "悟空", "age": 20, "permission": "wukong"}
    """
    permission = fields.String(required=True,validate=validate.OneOf(["read", "write", "admin"]))
    marshmallow.exceptions.ValidationError: {'permission': ['Must be one of: read, write, admin.']}
    """

    user_data = {"name": "悟空", "age": 20, "permission": "admin"}
    """
    permission = fields.String(required=True,validate=validate.OneOf(["read", "write", "admin"]))
    {'age': 20, 'permission': 'admin', 'name': '悟空'}
    """

    user_data = {"name": "悟空", "age": 20}

    us = UserSchema()
    # result = us.load(user_data)
    result = us.load(user_data, partial=True)  # 开发中会存在一些模型的数据在添加时是必填的，但在更新/修改时不需要必填
    print(result)

    return "hello"


if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0", port=5998)
